package org.zoomdev.zoom.protobuf.modules;

import io.protostuff.ByteArrayInput;
import io.protostuff.ProtostuffOutput;
import org.zoomdev.zoom.common.utils.Creators;

import java.io.IOException;
import java.util.Collection;

public final class CollectionSchema implements ISchema {

    private final ISchema schema;
    private final Class<?> type;

    public CollectionSchema(Class<?> type, ISchema schema) {
        this.schema = schema;
        this.type = type;
    }

    @Override
    public void write(ProtostuffOutput output, int index, Object value, boolean repeat) throws IOException {
        Collection iterable = (Collection) value;
        output.writeInt32(index, iterable.size(), false);
        for (Object data : iterable) {
            schema.write(output, index, data, true);
        }
    }

    @Override
    public Object mergeFrom(ByteArrayInput input) throws IOException {
        int len = input.readInt32();
        Collection list = Creators.newCollection(type);
        for (int i = 0; i < len; ++i) {
            input.readFieldNumber(null);
            Object value = schema.mergeFrom(input);
            list.add(value);
        }
        return list;
    }
}
